# -*- coding: utf-8 -*-

'''
2019年6月5日08:59:46
zhouzhongqing
获取ssr账号
'''

'''
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
去下载 ChromeDriver 
也可以在http://chromedriver.chromium.org/downloads 下载

selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. 
 下载地址 : geckodriver https://github.com/mozilla/geckodriver/releases

selenium文档 : https://selenium-python.readthedocs.io/ 
                中文 : https://selenium-python-zh.readthedocs.io/
'''
from selenium import webdriver
import os
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from bs4 import BeautifulSoup


# 写入文件
def write_to_file(file_name, txt):
    '''''
        讲txt文本存入到file_name文件中
    '''
    print("正在存储文件" + str(file_name));
    # 1 打开文件
    # w 如果没有这个文件将创建这个文件
    '''
    'r'：读

    'w'：写

    'a'：追加

    'r+' == r+w（可读可写，文件若不存在就报错(IOError)）

    'w+' == w+r（可读可写，文件若不存在就创建）

    'a+' ==a+r（可追加可写，文件若不存在就创建）
    '''
    f = open(file_name, 'a+', encoding='utf-8');
    # 2 读写文件
    f.write(str(txt));
    # 3 关闭文件
    f.close();


if __name__ == '__main__':
    print("start");
    folder_prefix = os.getcwd() + "/";
    driver = webdriver.Firefox()
    url = "https://free-ss.site/";
    gui_config_txt_path = "F:/software/ShadowsocksR-win-4.9.0/gui-config.json";
    all_ssr_account = [];
    driver.get(url);
    try:
        driver.implicitly_wait(30)
        # 得到table
        div_tbss_wrapper = driver.find_element_by_xpath("//div[@id='tbss_wrapper']").get_attribute("innerHTML");
        # print(div_tbss_wrapper);

        # 下滑
        # js = "var q=document.documentElement.scrollTop=1000"
        # driver.execute_script(js)

        # 初始化并制定解析器
        soup = BeautifulSoup(div_tbss_wrapper, "lxml");

        table = soup.table;
        tr_arr = table.find_all("tr");

        #寻找method和password的下标
        method_index = 0;
        password_index = 0;
        for tr_index_item in tr_arr:
            th_arr = tr_index_item.find_all("th");
            for th_item_index in range(len(th_arr)):
                '''
                V/T/U/M
                Address
                Port
                Method
                Password  
              '''
                if "Method" == th_arr[th_item_index].text:
                    method_index = th_item_index;

                if "Password" == th_arr[th_item_index].text:
                    password_index = th_item_index;
                print(th_arr[th_item_index].text + " index " + str(th_item_index) )


        for tr in tr_arr:
            # print(tr);
            # print("tr ----------------------");
            td_arr = tr.find_all("td");
            print(td_arr)
            if len(td_arr) >= 5:
                ssr_account = "{\n";
                ssr_account += "\"rearks\" : \"\",\n";
                ssr_account += "\"server\" : \"" + td_arr[1].text + "\",\n";
                ssr_account += "\"server_port\" : " + td_arr[2].text + ",\n";
                ssr_account += "\"server_udp_port\" : 0,\n";
                ssr_account += "\"password\" : \"" + td_arr[password_index].text + "\",\n";
                ssr_account += "\"method\" : \"" + td_arr[method_index].text + "\",\n";
                # ssr_account += "\"protocol\" : \"" + td_arr[5].text + "\",\n";
                ssr_account += "\"protocol\" : \"" + "origin" + "\",\n";
                ssr_account += "\"protocolparam\" : \"\",\n";
                # ssr_account += "\"obfs\" : \"" + td_arr[6].text + "\",\n";
                ssr_account += "\"obfs\" : \"" + "plain" + "\",\n";
                ssr_account += "\"obfsparam\" : \"\",\n";
                ssr_account += "\"group\" : \"free-ss.site\",\n";
                ssr_account += "\"enable\" : true,\n";
                ssr_account += "\"udp_over_tcp\" : false\n";
                ssr_account += ("}\n");
                all_ssr_account.append(ssr_account);

        # 如果存在先删除，现在是改名
        if os.path.exists(gui_config_txt_path):
            # print(" remove " + gui_config_txt_path)
            rename = gui_config_txt_path + time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime());
            print(" rename " + rename)
            os.rename(gui_config_txt_path, rename)
            # os.remove(gui_config_txt_path);

        os.chdir(folder_prefix);
        prefix = open("./prefix");
        prefix_str = "";
        for line in prefix:
            prefix_str += line;
        write_to_file(gui_config_txt_path, prefix_str + "\n");

        all_ssr_account_str = "";
        for index in range(len(all_ssr_account)):
            # print(item + "\n");
            punctuation = "";
            if str(index) != str(len(all_ssr_account) - 1):
                # 判断是否要增加逗号
                punctuation = ",";
            all_ssr_account_str += all_ssr_account[index] + punctuation + "\n";

        write_to_file(gui_config_txt_path, all_ssr_account_str + "\n");

        suffix = open("./suffix");
        suffix_str = "";
        for line in suffix:
            suffix_str += line;

        # print(suffix_str);
        write_to_file(gui_config_txt_path, suffix_str + "\n");
    finally:
        print("finally")
        # driver.quit();

    print("end");
    random_input = input("请输入任意字符串结束.");
    driver.quit();
	
